package com.atguigu.gulimall.product.app;

import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.Catelog2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

@Controller
public class IndexController {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedissonClient redisson;

    @GetMapping({"/","/index.html"})
    public String indexPage(Model model){
        // 查询所有一级分类
        List<CategoryEntity> categoryEntityList = categoryService.getCatelogLevel1();
        model.addAttribute("categorys",categoryEntityList);
        return "index";
    }


    @GetMapping("/index/json/catalog.json")
    @ResponseBody
    public Map<String, List<Catelog2Vo>> getCatalogJson(){
        Map<String, List<Catelog2Vo>> map = categoryService.getCatalogJson();
        return map;
    }


    /**
     *  lock.lock() 阻塞式等待，默认加的锁都是30s
     *  锁的自动续期，如果业务时间超长，运行期间自动给锁续上新的30s
     *
     *  lock.lock(10,TimeUnit.SECONDS)。在锁到期之后不会自动续期
     *  lock.lock() 默认在 看门狗的1/3时间之后有定时任务自动续期
     *
     *  最佳实战 -> 使用 lock.lock(long time,TimeUnit timeunit);
     * @return
     */
    @ResponseBody
    @GetMapping("/test")
    public String test(){
        RLock lock = redisson.getLock("my-lock");
        lock.lock();
        try{
            System.out.println("加锁成功，执行业务...");
            TimeUnit.SECONDS.sleep(10);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            // 解锁
            lock.unlock();
        }
        return "hello";
    }
}
